package com.simon.mctm.config;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * @author Jiajie.Mao
 * @date 2018/6/8 16:05
 **/
@Configuration
@EnableTransactionManagement
public class TransactionManagerConfig {

	/**
	 * 下面两个方法是注解式开启事务
	 */
	@Bean(name = "transactionInterceptor")
	public TransactionInterceptor transactionInterceptor(
	        PlatformTransactionManager platformTransactionManager) {
	    TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
	    // 事物管理器
	    transactionInterceptor.setTransactionManager(platformTransactionManager);
	    Properties transactionAttributes = new Properties();
	    // 新增
	    transactionAttributes.setProperty("insert*","PROPAGATION_REQUIRED,-Throwable");
	    // 修改
	    transactionAttributes.setProperty("update*","PROPAGATION_REQUIRED,-Throwable");
	    // 删除
	    transactionAttributes.setProperty("delete*","PROPAGATION_REQUIRED,-Throwable");
	    //查询
	    transactionAttributes.setProperty("select*","PROPAGATION_SUPPORTS,-Throwable,readOnly");
	    transactionInterceptor.setTransactionAttributes(transactionAttributes);
	    return transactionInterceptor;
	}

	@Bean
	public BeanNameAutoProxyCreator transactionAutoProxy() {
	    BeanNameAutoProxyCreator transactionAutoProxy = new BeanNameAutoProxyCreator();
	    transactionAutoProxy.setProxyTargetClass(true);
	    transactionAutoProxy.setBeanNames("*ServiceImpl");
	    transactionAutoProxy.setInterceptorNames("transactionInterceptor","druid-stat-interceptor");
	    return transactionAutoProxy;
	}
     
}
